package com.hengxinguotong.zhihuichengjian.ui.quality;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.QualityAccidentListAdapter;
import com.hengxinguotong.zhihuichengjian.bean.SecurityAccident;
import com.hengxinguotong.zhihuichengjian.bean.SecurityAccidentRes;
import com.hengxinguotong.zhihuichengjian.treeview.RecyclerAdapter;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.ui.security.SecurityAccidentActivity;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshBase;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshListView;
import com.hengxinguotong.zhihuichengjian.widget.view.PullableRecyclerView;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 质量事故列表 安全事故列表
 * Created by liux on 2017/3/7.
 */

public class QualityAccidentListActivity extends BaseActivity {
    @BindView(R.id.title_tv)
    HXTextView titleTv;
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.add)
    HXTextView add;
    @BindView(R.id.refresh_list)
    PullToRefreshLayout refreshList;

    private PullableRecyclerView dataRv;

    private QualityAccidentListAdapter qualityAccidentListAdapter;
    private int pageIndex = 1;
    private List<SecurityAccident> securityAccidents;
    private String interfaceString;
    private int type = 1;//1 质量  2安全
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case Constants.UPDATE:
                    List<SecurityAccident> datas = (List<SecurityAccident>) msg.obj;
                    addData(datas);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quality);
        ButterKnife.bind(this);
        type = getIntent().getIntExtra("type", Constants.QUALITY);
        initView();
        initData();
    }

    private void initView() {
        if(hasAdd()){
            add.setVisibility(View.VISIBLE);
        }
        switch (type) {
            case Constants.QUALITY:
                titleTv.setText("质量事故列表");
                break;
            case Constants.SECURITY:
                titleTv.setText("安全事故列表");
                break;
        }

        refreshList.setPullUpEnable(false);
        refreshList.setOnPullListener(pullListener);
        dataRv = (PullableRecyclerView) refreshList.getPullableView();
        securityAccidents = new ArrayList<>();
        qualityAccidentListAdapter = new QualityAccidentListAdapter(this, securityAccidents);
        qualityAccidentListAdapter.setClickListener(clickListener);
        dataRv.setAdapter(qualityAccidentListAdapter);
        dataRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
    }

    private void initData(){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getTestList("加载中…");
            }
        }, 500);
    }

    private PullToRefreshLayout.OnPullListener pullListener = new PullToRefreshLayout.OnPullListener()
    {
        @Override
        public void onRefresh(PullToRefreshLayout pullToRefreshLayout)
        {
            pageIndex = 1;
            initData();
        }

        @Override
        public void onLoadMore(PullToRefreshLayout pullToRefreshLayout)
        {
            pageIndex = securityAccidents.size() / Utils.ONCECOUNT + 1;
            initData();
        }
    };

    private QualityAccidentListAdapter.ClickListener clickListener = new RecyclerAdapter.ClickListener() {
        @Override
        public void onClick(int position) {
            Intent intent = new Intent(QualityAccidentListActivity.this, SecurityAccidentActivity.class);
            intent.putExtra("type", type);
            intent.putExtra("securityaccident", securityAccidents.get(position));
            startActivity(intent);
        }
    };

    @OnClick({R.id.iv_back, R.id.add})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.add:
                intent = new Intent(this, SecurityAccidentActivity.class);
                intent.putExtra("type", type);
                startActivityForResult(intent, 1);
                break;
        }
    }

    //获取事故列表信息
    private void getTestList(String alert) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("constructionId", SPUtil.getString(this,"constructionid"));
            jsonObject.put("pageNum", pageIndex + "");
            jsonObject.put("type", type + "");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


        Utils.requestData(alert, this, "/accidentReport/queryByConstructionId/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    SecurityAccidentRes res = gson.fromJson(json, SecurityAccidentRes.class);
                    if(res.getStatus() == 1){
                        Message message = handler.obtainMessage();
                        message.obj = res.getValue();
                        message.what = Constants.UPDATE;
                        message.sendToTarget();
                    }else{
                        showToast(res.getMsg());
                        if (pageIndex == 1)
                        {
                            refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                        } else
                        {
                            refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                        }
                    }
                }else{
                    showToast("系统异常");
                    if (pageIndex == 1)
                    {
                        refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                    } else
                    {
                        refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
                if (pageIndex == 1)
                {
                    refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                } else
                {
                    refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1) {
            initData();
        }
    }

    private void addData(List<SecurityAccident> datas) {
        if (pageIndex == 1)
        {
            refreshList.refreshFinish(PullToRefreshLayout.SUCCEED);
            securityAccidents = datas;
        } else
        {
            refreshList.loadmoreFinish(PullToRefreshLayout.SUCCEED);
            securityAccidents.addAll(datas);
        }
        if (datas.size() >= Utils.ONCECOUNT)
        {
            refreshList.setPullUpEnable(true);
        } else
        {
            refreshList.setPullUpEnable(false);
        }
        qualityAccidentListAdapter.setDataList(securityAccidents);
    }
}
